const
#include<iostream>
using namespace std;
//类中包含const成员变量 要在初始化列表中初始化
class AA
{
public:
const int a;
int b;
public:
AA() : a(100) //初始化列表比在函数中赋值的要早
{
b = 200;
}
public:
void Show()
{
cout << a << endl;
b = 300;
cout << b << endl;
}
void ShowShow() const;//仅在类中使用
};
void AA::ShowShow(/* const AA * const this*/) const//常函数的实现 本身应该是 AA * const 类型的
{
cout << a << endl;
/*b = 300;*/ //this指针变成常量了 所以找不到b 所以改不了值
cout << b << endl;
}
//在类成员函数的后面加一个const 表示该函数为常函数
//const放在函数返回值前 表示函数返回值是一个常量
//常函数限制了this指针 不能通过this指针去修改当前对象中的成员变量
//常对象只能调用常函数
int main()
{
AA a;
a.Show();
a.ShowShow();
const AA b; //b的类型是const AA类型的 指针类型则为 const AA*类型的 则为 const AA* const this
//b.Show();
b.ShowShow();
system("pause");
return 0;
}
class与struct的区别
#include<iostream>
using namespace std;
//struct AA
//struct BB
//{
// int a;
// void (*pShow)(BB*);
//};
//void Show(BB * th)
//{
//
//}
class AA
{
int a;
AA()
{
a = 100;
}
void Show()
{
cout << a << endl;
}
};
//c++中 struct 可以有构造函数和析构函数 可以有成员函数
//在stuct中也有访问修饰符
//class 默认访问修饰符为private struct 默认访问修饰符为public
//class 继承默认是private struct 默认继承是public
//class 可以使用模板 struct 不能
int main()
{
/*AA a;
a.Show();*/
system("pause");
return 0;
}
string
#include<iostream>
#include<string>
using namespace std;
int main()
{
/*string str = "abcd";
string str1 = "1234";
cout << str << endl;
string str2 = str + str1;
cout << str2 << endl;
str = str1;
cout << str << endl;
if (str == str1)
{
cout << "一样" << endl;
}
else
{
cout << "不一样" << endl;
}*/
//char str[] = "abcd";
//char* str1 =(char*)"abcde";
////strcpy_s = strcat_s + strcmp ==
//char* str2 = new char[10];//str2 指向堆区
//str2 = (char*)"12345"; //str2指向字符常量区 堆区内存泄漏 空间丢失 找不到堆区那块空间了
//cout << str2 << endl;
string str = "abcd"; //string是类名 所以std是对象
//char* p = (char*)str.c_str();//返回当前对象中真实的字符串的地址
//cout << p << endl;
//str.append("1234");//追加一个字符串
//cout << str << endl;
//str.push_back('A');//追加一个字符
//cout << str << endl;
//
str.size();//返回字符串的长度
cout << str.size() << endl;
cout << str.length() << endl;//与size没区别
str.insert(3,"1234");//参数 (插入位置,字符串)
cout << str << endl;
system("pause");
return 0;
}