#include <iostream>
#include <string>
class Value
{
private:
std::string value;
public:
Value() {
std::cout << "default construct" << std::endl;
}
Value(std::string str) :value(str) {
std::cout << "construct: value is " << str << std::endl;
}
};
class Test
{
private:
Value m_v;
public:
Test(Value v)
{
m_v = v;
}
};
int main(int argc, char **argv)
{
Test t(Value("hello world"));
return 0;
}
输出:
#include <iostream>
#include <string>
class Value
{
private:
std::string value;
public:
Value() {
std::cout << "default construct" << std::endl;
}
Value(std::string str) :value(str) {
std::cout << "construct: value is " << str << std::endl;
}
};
class Test
{
private:
Value m_v;
public:
Test(Value v):m_v(v)
{
}
};
int main(int argc, char **argv)
{
Test t(Value("hello world"));
return 0;
}
输出:
不需要调用默认构造函数