对于没有复制类,我可以更改代码,以便VS2010编译器在违规行上标记错误吗?

时间:2010-09-26 23:12:30

标签: c++ visual-studio-2010

我可以更改代码,以便VS2010编译器的错误消息指向有问题的代码行吗?

class NoCopy
{ //<-- error shows up here
   NoCopy( const NoCopy& ); //<-- and error shows up here
   NoCopy& operator=( const NoCopy& );
 public:
   NoCopy(){};
};

struct AnotherClass :NoCopy
{
}; //<-- and error shows up here

int _tmain(int argc, _TCHAR* argv[])
{
  AnotherClass c;
  AnotherClass d = c; //<-- but the error does not show up here
  return 0;
}

请注意'NoCopy(const NoCopy&amp;)= delete;'在VS2010中无法编译。 我不能用boost。

这是根据Micheal的建议添加的:

1>------ Build started: Project: Test, Configuration: Debug Win32 ------
1>  Test.cpp
1>c:\Test\Test.cpp(16): error C2248: 'NoCopy::NoCopy' : cannot access private member declared in class 'NoCopy'
1>          c:\Test\Test.cpp(8) : see declaration of 'NoCopy::NoCopy'
1>          c:\Test\Test.cpp(7) : see declaration of 'NoCopy'
1>          This diagnostic occurred in the compiler generated function 'AnotherClass::AnotherClass(const AnotherClass &)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

2 个答案:

答案 0 :(得分:1)

错误未显示在正确的行中,因为Visual Studio不知道它来自何处,这是自动编译的AnotherClass(const AnotherClass&)。您必须明确定义它,以便Visual Studio继续查找错误的来源。

class NoCopy {
   NoCopy( const NoCopy& );
   NoCopy& operator=( const NoCopy& );
 public:
   NoCopy(){};
};

struct AnotherClass :NoCopy
{
    AnotherClass();  // Since there is another constructor that _could_ fit,
                     // this also has to be defined
private:
    AnotherClass(const AnotherClass&);  // Define this one
};

int _tmain(int argc, _TCHAR* argv[])
{
  AnotherClass c;
  AnotherClass d = c; //<-- error is now shown here
  return 0;
}

您现在可以获得:

  

1&gt; \ main.cpp(20):错误C2248:'AnotherClass :: AnotherClass':无法访问类'AnotherClass'中声明的私有成员

指的是“正确的”行。

答案 1 :(得分:0)

这是我在尝试编译时遇到的唯一错误:

Error   1   error C2248: 'NoCopy::NoCopy' : cannot access private member declared in class 'NoCopy' main.cpp    11  1

如果你将构造函数设为public,它编译得很好(当然,由于缺少这些成员函数的实现,它无法链接)。

我可以猜测一下你的意思:为什么构造函数存在访问错误,而=运算符却没有?答案是第二行被视为构造函数而不是赋值。