C++4種類のコンストラクタが呼び出されるタイミング
3333 ワード
コピー、割り当て、コンテナ
継承中
オペレータリロード
#include
#include
#include
継承中
#include
using std::cout;
using std::endl;
class Base
{
public:
Base()
{
cout << "No param" << endl;
}
Base(int a)
{
cout << "with param" << endl;
}
private:// COPY Private COPY
Base(const Base &b)
{
cout << "copy" << endl;
}
};
class Derived:public Base
{
public:
Derived()//
{
}
Derived(int a):Base(a)
{}
};
int main()
{
Derived a;
Derived b(2);
// Derived c = a;
cout << "main" << endl;
return 0;
}
オペレータリロード
#include
#include
using namespace std;
//
class Book
{
private:
unsigned int mId;
string mName;
public:
Book(unsigned int id, string name);
Book(const Book &book);
Book &operator=(const Book &book);
ostream &operator<mId << endl;
os << "name:" << this->mName << endl;
return os;
}
ostream &operator<mName + book.mName;
return tmp;
}
Book operator-(Book &book1, Book &book2)
{
Book tmp(0,"");
tmp.mName = book1.mName + "-" + book2.mName;
return tmp;
}
int main()
{
Book hualuo(1, "hua luo zhi duo shao");
Book zhiduoshao(2, "zhi duo shao");
Book hualuo_copy = hualuo;//copy
hualuo_copy = hualuo;//assign
hualuo_copy << cout;
cout << hualuo << endl;
Book total = hualuo + zhiduoshao;
cout << total << endl;
Book minu = hualuo - zhiduoshao;
cout << minu << endl;
return 0;
}