【问题标题】:Program compiling on Visual Studio 2010 but not on VS 2015程序在 Visual Studio 2010 上编译,但不在 VS 2015 上
【发布时间】:2017-06-13 07:38:39
【问题描述】:

我正在开发一个几年前用 VS 2010 用 C++ 编写的软件,当我现在想编译它时,它会显示错误。我准确地说,如果你使用 VS 2010,它仍然有效,但我的工作中只有 2015 年。

我做了一个简单的代码来显示错误,它涉及一个模板类tab1D,它继承自vector并重新定义了诸如“()”之类的运算符。

这是简化的代码:

简单的主要:

#include <iostream>
#include "memory_tab.h"
using namespace std;

int main() {
    cout << "Hello" << endl;
    tab1D<int> t (2);
    cout << "Initialization works fine" << endl;
    cout << t[1] << endl;
    cout << "Bracket operator works fine" << endl;
    cout << t(1) << endl; // this line calls parenthesis operator which is overwritten in memory_tab.h. It does not compile.
    cout << "Error C3867 & C2100" << endl;
    int a;
    cin >> a;
    return 0;
}

memory_tab.h:

//includes and stuff    
template <class T>
class tab1D : public vector<T>
{
public:
//  //Constructors
//  /*!
//   * \brief Default constructor (set nbElem and tailleMem to 0)
//   */
    tab1D() : vector<T>() {};
    tab1D(int _nbElem) : vector<T>(_nbElem) {}; // set all elements to 0

//  //Operators
    T& operator() (unsigned val); 
    T& operator() (unsigned val) const;

};

template <class T> T& tab1D<T>::operator() (unsigned val)
{
    return *(_Myfirst + val);
}

template <class T> T& tab1D<T>::operator() (unsigned val) const
{
    return *(_Myfirst + val);
}

当我尝试编译它时,它在运算符 () 的返回处显示错误 C3867C2100。但是这些现在似乎没有任何理由弹出:_Myfirst是vector类的属性,应该可以。

我该如何解决这个问题(实际文件超过 3000 行,有 600 个错误,总是 C3867 和 C2100),我可以在 VS 2015 和 VS 2010 之间的某种兼容模式下工作吗?

谢谢。

【问题讨论】:

  • 我自己在理解编译器消息时遇到了一些麻烦。当你去掉条件编译时,你的minimal reproducible example 会发生什么?从const 方法返回非const 引用应该不起作用。
  • 谢谢。 Burr 先生似乎同时解决了这个问题,但在 const 版本的 operator() 中,您仍然会遇到返回类型的问题
  • 是的,我改变了在返回之前复制我想要返回的值。

标签: c++ visual-studio-2010 visual-studio-2015 stl


【解决方案1】:

您的代码依赖于std::vector 类的内部实现细节,即_Myfirst 成员。

std::vector 的实现在 VS2010 和 VS2015 之间发生了变化,因此 _Myfirst 在 VS2010 中是一个简单的指针,但在 VS2015 中是一个返回对指针的引用的成员函数。

您应该编写代码,使tab1D 类仅使用std::vector 的公共非内部接口(您可能已经使用APP_LINUX 块中的代码)。

【讨论】:

  • 确实,无论是使用linux版本,还是在_Myfirst加括号都可以消除错误,谢谢!
  • 最好接受不使用内部库实现细节的建议。这些东西可能会在您不经通知的情况下从您身下发生变化。
  • 是的,我没有写那个代码,不过会改变它以适应标准
猜你喜欢
  • 1970-01-01
  • 2021-01-09
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多