C++ 与 gcc 和 visual studio 的不同编译错误, 'within this context'

标签 c++ visual-studio-2010 gcc compiler-errors

我之前发过类似的问题,但是我的代码有一点小错误,所以忽略了,让我再问一次。

在 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:\users\user\documents\visual studio 2012\projects\tester\tester\objectholder.h(13): 

     error C2248: 'NonCopyableObject::NonCopyableObject' : cannot access private member declared in   class 'NonCopyableObject'
               d:\users\user\documents\visual studio 2012\projects\tester\tester  
     \noncopyableobject.h(13) : see declaration of 'NonCopyableObject::NonCopyableObject'
            d:\users\user\documents\visual studio 2012\projects\tester\tester
     \noncopyableobject.h(6) : see declaration of 'NonCopyableObject'
            This diagnostic occurred in the compiler generated function    
     'ObjectHolder::ObjectHolder(const ObjectHolder &)'

海湾合作委员会:

$ 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 的对象,该对象具有私有(private)复制构造函数。

默认情况下,生成的复制构造函数调用所有成员对象和父对象的复制构造函数。

关于C++ 与 gcc 和 visual studio 的不同编译错误, 'within this context',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359756/

相关文章:

c++ - 调用由 void 指针引用的对象的函数

sql-server - 如何禁用即时调试器?

visual-studio-2010 - 在 Visual Studio 或 resharper 中运行单元测试用例之前是否可以避免构建

visual-studio-2010 - 如果参数为空则显示全部 Crystal Reports

c++ - 从 C++ I/O 中的字符串行读取 "tokens"

C++ SFML : How to successfully Iteratively render shapes?

c++ - 我是否需要做一些特别的事情来让我的 C++ 程序使用 gcc 进行编译?

gcc - 无法在 Ubuntu 10.04 上构建 Node.js

gcc - 使用 Yocto 交叉编译 GCC 和 GDB

c++ - MPI-Ibcast 用法