错误 5 错误 C2535 成员函数已定义或声明.视觉工作室 2013.

Error 5 error C2535 member function already defined or declared. VisualStudio 2013

本文关键字:错误 声明 视觉 工作室 2013 C2535 成员 函数 定义      更新时间:2023-10-16

我在这段代码上遇到了一些问题,我的Visual Studio 2013通知此错误:"错误5错误C2535成员函数已定义或声明"。我在代码上标记了它发生的确切位置。

#ifndef __NORMAL_H_INCLUDED__
#define __NORMAL_H_INCLUDED__
class Normal{
public:
    double x;
    double y;
    double z;
    Normal(double x, double y, double z);
    Normal(double x, double y);
    Normal();
};
#endif
#include "Normal.h"
Normal::Normal(double x=0, double y=0, double z=0){
    this->x = x;
    this->y = y;
    this->z = z;
}

Normal::Normal(double x=0, double y=0){
    this->x = x;
    this->y = y;
    this->z = 0;
} // ERROR HERE = Error 5 error C2535 member function already defined or declared
Normal::Normal(){
    x=0;
    y =0 ;
    z =0;
}

使用 clang++ 编译代码会给出此错误:

normal.cpp:12:23: error: addition of default argument on redeclaration makes this
      constructor a default constructor
Normal::Normal(double x=0, double y=0, double z=0){ 
                      ^ ~
normal.cpp:7:5: note: previous declaration is here
    Normal(double x, double y, double z);
    ^
normal.cpp:19:23: error: addition of default argument on redeclaration makes this
      constructor a default constructor
Normal::Normal(double x=0, double y=0){
                      ^ ~
normal.cpp:8:5: note: previous declaration is here
    Normal(double x, double y);

这可能是一个好的说法。编译器无法区分:

Normal n = Normal();

Normal m = Normal(0, 0);

Normal o = Normal(0, 0, 0);

如果您始终希望参数为零填充,只需使用一种形式:

class Normal{
public:
    double x;
    double y;
    double z;
    Normal(double x = 0, double y = 0, double z = 0);
};

永远不要将默认参数放在实现部分,无论您是否在标头中都有它们,因为诱惑是在实现或标头中分别更改它们,然后你会得到非常混乱的结果。

当然,您可能要考虑使用两个或三个不同版本的构造函数,而不是默认值。但是从中选择一个。或者使用具有一个"必须具有"值和一个"未指定值"的构造函数。传递参数当然会在调用代码中添加更多代码,因此在大型项目中,使用不同数量的对象多次创建Normal对象,传递三个double参数和不传递任何参数之间可能存在显着的大小差异。

我应该补充一点,代码在 4.8.2 版本中g++编译良好。这可能是一个错误...