错误5错误已定义或声明了C2535成员函数。 VisualStudio 2013

时间:2014-11-15 10:33:35

标签: c++ visual-studio-2013

我在使用此代码时出现问题,我的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;
}

1 个答案:

答案 0 :(得分: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);
};

永远不要在实现部分中放置默认参数,无论是否在标题中都有它们,因为诱惑将是在实现或标题中单独更改它们,然后您会得到非常令人困惑的结果。

您当然可以考虑使用两个或三个不同版本的构造函数,而不是默认值。但选择其中一个。或者使用带有一个"的构造函数必须有"值,并且没有指定值#34;传递参数当然会在调用代码中添加更多代码,因此在大型项目中,Normal个对象被创建多次具有不同数量的对象,传递三个{double之间的大小可能会有很大差异。 1}}参数,不传递任何参数。

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