c++学习——c++下结构体的加强和更加严格的类型转换、c与c++三目运算符对比

结构体加强

加强一︰定义变量时不需要使用struct
加强二:结构体内可以写函数

#define _CRT_SECURE_NO_WARNINGS
#include 
using namespace std;

//加强1
//自定义数据类型
//此时定义的是结构体  他是数据类型  不占内存空间
struct Maker
{
	char name[64];
	int age;
};

void test01()
{
	//不需要加struct就可以定义变量
	Maker a;//定义完变量一后才会有内存空间的占用
	a.age = 19;
	cout << a.age << endl;
}

//加强二 
struct Maker2
{
	int a;
	void func()//结构体内可以写函数
	{
		cout << "func" << endl;
	}
};
void test02()
{
	Maker2 a2;
	a2.func();
}

int main()
{
	test01();
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

更加严格的类型转换

#define _CRT_SECURE_NO_WARNINGS
#include 
using namespace std;

int main()
{	
	//这种方式不能进行隐式转换,必须显示的转换
	//char *p = malloc(64);   //c语言下
	char *p = (char *)malloc(64); //c++下
	system("pause");
	return EXIT_SUCCESS;
}

三目运算符

c语言下的三目运算符

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 

void test01()
{
	int a = 10;
	int b = 20;
	printf("%d\n", a > b ? a : b);
	//(a>b?a:b)=100   err
	//这个表达式返回的是右值
	//20=100  
	*(a > b ? &a : &b) = 100;
	printf("%d\n", b);
}
int main()
{
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

在这里插入图片描述

c++下的三目运算符

#define _CRT_SECURE_NO_WARNINGS
#include 
using namespace std;
void test02()
{
	int a = 10;
	int b = 20;
	(a > b ? a : b) = 100;
	//这个表达式返回的是左值  是空间
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}
int main()
{
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

在这里插入图片描述
c语言的三目运算符返回的是右值
C++语言的三目运算符返回的是左值,是空间放在赋值操作符左边的是左值,放在右边的是右值

你可能感兴趣的:(c++学习,c++,学习,开发语言)