我以前贴过一个类似的问题,但我在代码中有一个小错误,所以它被忽略了,让我再问一次。
在Gcc中,我得到了编译错误的确切行在VS2010/2012我不知道编译错误在哪里,有人能帮助吗?**在VS中,我怎么知道哪一行调用了它?
我有以下代码:
#include "ObjectHolder.h"
int main()
{
ObjectHolder first(1);
ObjectHolder second(first);
return 0;
}
#ifndef NonCopyableObject_Included
#define NonCopyableObject_Included
class NonCopyableObject
{
public:
virtual ~NonCopyableObject () {}
NonCopyableObject(int i) { m_index = i;}
int m_index;
private:
NonCopyableObject(const NonCopyableObject& other) {}
};
#endif
#ifndef ObjectHolder_Included
#define ObjectHolder_Included
#include "NonCopyableObject.h"
class ObjectHolder
{
public:
virtual ~ObjectHolder ();
ObjectHolder(int i) : obj(i) {}
NonCopyableObject obj;
};
#endif
VS错误:1>d:usersuserdocumentsvisual studio 2012projectstestertesterobjectholder.h(13):
error C2248: 'NonCopyableObject::NonCopyableObject' : cannot access private member declared in class 'NonCopyableObject'
d:usersuserdocumentsvisual studio 2012projectstestertester
noncopyableobject.h(13) : see declaration of 'NonCopyableObject::NonCopyableObject'
d:usersuserdocumentsvisual studio 2012projectstestertester
noncopyableobject.h(6) : see declaration of 'NonCopyableObject'
This diagnostic occurred in the compiler generated function
'ObjectHolder::ObjectHolder(const ObjectHolder &)'
GCC:
$ g++ -Wall -Werror --std=c++0x main.cpp -o test_no_copy
In file included from main.cpp:2:0:
NonCopyableObject.h: In copy constructor `ObjectHolder::ObjectHolder(const ObjectHolder&)':
NonCopyableObject.h:13:3: error: `NonCopyableObject::NonCopyableObject(const NonCopyableObject&)' is private
ObjectHolder.h:7:1: error: within this context
main.cpp: In function `int main()':
main.cpp:8:27: note: synthesized method `ObjectHolder::ObjectHolder(const ObjectHolder&)' first required here
编译器不能在ObjectHolder
中生成(合成)复制构造函数,因为它包含一个具有私有复制构造函数的NonCopyableObject
类的对象。
默认情况下,生成的复制构造函数调用所有成员对象和父对象的复制构造函数。
使用不同的编译器进行编译是一个好主意,因为不同的编译器之间的错误差异很大,其中一个可能比另一个更有帮助。在大多数情况下,我发现Clang的错误报告是最好的。在您的示例中:
source.cpp:9:48: error: unused parameter 'other' [-Werror,-Wunused-parameter] NonCopyableObject(const NonCopyableObject& other) {} ^ source.cpp:25:18: error: call to implicitly-deleted copy constructor of 'ObjectHolder' ObjectHolder second(first); ^ ~~~~~ source.cpp:18:23: note: copy constructor of 'ObjectHolder' is implicitly deleted because field 'obj' has an inaccessible copy constructor NonCopyableObject obj;
您正在尝试复制ObjectHoder
ObjectHolder second(first);
但是它包含一个不可复制的对象,所以它不能被复制。您正在尝试执行代码在编译时被设计为不允许的操作。两个编译器都告诉你这个