非静态成员函数是否可以具有与其内部定义的类相同的类型?
Can a non-static member function have the same type as that of class it is defined inside?
非静态成员函数可以具有与其内部定义的类相同的类型吗?
请给我解释一下,因为我是编程新手
//defining class complex and adding it
class complex
{
private :
int real;
int imaginary;
public:
complex(){}
complex(int x1,int x2);
void display();
complex add(complex n1,complex n2) // can this member function be of complex? type
{
complex temp;
temp.real=n1.real+n2.imaginary;
return temp;
}
}
没有这样的限制。成员函数可以有任何普通函数可以接受的返回类型。
你的例子将工作,但它是没有意义的这种add
函数为,因为它不会使用被调用对象的状态。
例如:
complex a,b,c,d;
a = b.add(c,d);
a
是对c
和d
进行操作的结果。不涉及b
。
任何成员函数的返回类型都可以是声明它的类类型。以operator =
重载为例。operator =
是类的非静态成员函数。
complex & operator =( const complex & )
{
// some stuff
return *this;
}
当然可以。但是在您的函数add()
中,它是静态成员函数还是非静态成员函数并不重要,因为您不使用调用对象的成员。您可能会发现它对代码更有表现力:
complex operator+(complex operand)
{
return complex(real + operand.real, imaginary + operand.imaginary);
}
那么您将能够以一种自然而富有表现力的方式使用'+'操作符,例如:
complex a(1,2);
complex b(3,4)
complex c = a + b;
在这种情况下,operator+
方法将被a
调用,并且在操作符体中,成员变量real
和imaginary
将隐式地成为a
的成员,b
将由operand
表示。
非静态成员函数可以与类名具有相同的类型吗?
* complex add(complex n1,complex n2)//该成员函数是否为复型
是最简单的答案
相关文章:
- 如何理解c++中在命名空间内部定义的枚举类型enum
- 在模板类内部定义的枚举上的嵌套类的部分专用化
- 静态指针指向这个为mock for googletest定义的类内部
- 为什么在匿名名称空间中定义的模板时,为什么内部链接错误
- C++构造函数具有内部链接,但未定义 [-Wundefined-internal]
- 静态数组溢出堆栈(seg 错误 11)仅在类定义内部时,否则不会..?
- 使用包含该结构内部结构的 using 定义
- G++ 自定义任务在外部终端中打开,与 VS 代码内部终端
- 类定义内部"error: 'a' does not name a type"
- IFDEF块内部对功能的未定义引用
- 有符号整数溢出、内部函数和未定义的行为
- 是定义的函数参数的内部执行顺序
- 在哪里放置 PRIVATE 嵌套(内部)类的非成员函数定义
- 为什么SFINAE(enable_if)从类定义内部工作而不是从外部工作
- Sendmessage在方法定义内部无法正常工作
- 内联方法:类定义内部与外部类定义
- 常量静态成员初始化 - 类定义内部与外部类定义
- 在结构定义内部声明结构的堆栈
- 在C++中,在类定义内部或外部定义方法体是否更为传统
- 在类定义内部和外部定义成员函数之间有区别吗