据我所知C++
,我们不能将相同的identifier
用于另一个声明:
int x;
char x; // compile-time error: redefinition.
但是这里有一个例子,我正在弄乱classes
:
#include "stdafx.h"
#include <iostream>
#include <vector>
class A {
public:
A(int);
void print()const;
friend std::ostream& operator << (std::ostream& out, A& rhs);
private:
int value1;
};
std::ostream& operator << (std::ostream& out, A& rhs) {
out << "rhs.value1 = " << rhs.value1 << std::endl;
return out;
}
A::A(int x) : value1(x) { std::cout << "ctor A(x)" << std::endl; }
void A::print()const {
std::cout << "value1: " << value1 << std::endl;
}
int A(int x) {
std::cout << "inside A(int x)" << std::endl;
return x;
}
int main(){
class A a { 0 };
a = A(7);
a.print();
std::cout << A(7) << std::endl;
std::cout << A(5) << std::endl; // here if I comment out the function a it is ok as long as I overloaded the insertion operator
// and if I add the function A it hides the insertion operator!
std::cout << std::endl;
std::cin.get();
return 0;
}
因此,正如您在上面看到的那样,每当我声明class
的对象时,我必须添加关键字class A
,否则会出现编译时错误。为什么呢?
a = A(7);
是函数调用,返回值是否传递给采用整数的class A
构造函数。或者只是没有函数调用,只有ctor
调用?答案 0 :(得分:0)
从我的角度来看,你有一个A类和一个函数A,所以你必须指出A是一个类或一个函数,这就是为什么你必须添加&#34; class&#34;当你声明一个A的对象时。
根据以下代码,定义了两个类A和B,它们完全相同,但A可以是函数或类,因此当您声明对象A时,您必须添加&#34 ;类&#34;在A之前,声明B的对象时不需要添加&#34;类&#34;
对于第二个问题,调用第一个函数A,其返回值用于构造对象a。你可以看到第一个x = 7在函数A中,而ctor x = 8因为函数返回x + 1.
输出:
@Entity
@Table(name = "friendship")
public class Friendship {
@Id
private Long id;
@ManyToOne
@JoinColumn(name="owner_id", referencedColumnName = "id", nullable = false, updatable = false)
private User owner;
@ManyToOne
@JoinColumn(name="friend_id", referencedColumnName = "id", nullable = false, updatable = false)
private User friend;
测试代码:
ctor A(x) x=0
inside A(int x) x=7
ctor A(x) x=8
ctor B(x)