如何初始化具有引用的类的构造函数的副本构造函数。我只是不知道在冒号后面放什么来初始化它。
class Me{
public:
Me (const otherMe& t)
:other_me(t)
{}
//copy constructor
Me(const Me& me)
: /*what do you put here in order to write
the line of code bellow. I tried t(t), and gives me the
warning 'Me::t is initialized with itself [-Winit-self]' */
{cout << t.getSomthing() << endl;}
private:
const otherMe& other_me;
};
答案 0 :(得分:2)
假设您有两个课程,void SomeMethod<T>(List<T> oldRecords, List<T> newRecords, List<string> propertiesOfT)
{
// get the list of property to match
var properties = propertiesOfT.Select(prop => typeof(T).GetProperty(prop)).ToList();
// Get all old record where we don't find any matching new record where all the property equal that old record
var notMatch = oldRecords.Where(o => !newRecords.Any(n => properties.All(prop => prop.GetValue(o).Equals(prop.GetValue(n))))).ToList();
}
和public class test
{
public int id { get; set; } = 0;
public string desc { get; set; } = "";
public test(string s, int i)
{
desc = s;id = i;
}
}
private void Main()
{
var oldRecords = new List<test>()
{
new test("test",1),
new test("test",2)
};
var newRecords = new List<test>()
{
new test("test1",1),
new test("test",2)
};
SomeMethod(oldRecords, newRecords, new List<string>() { "id", "desc" });
}
:
Value
我们可以这样编写构造函数和复制构造函数:
Wrapper
如果class Value { // stuff... };
class Wrapper; // This one contains the reference
是一个const引用,此方法也可以使用!此外,如果您可以将class Wrapper {
Value& val;
public:
Wrapper(Value& v) : val(v) {}
Wrapper(Wrapper const& w) : val(w.val) {}
};
汇总编写,它将自动获得一个副本构造函数:
Value&