bool operator== (book a, book b) {
if (a.code == b.code) { return true; }
else { return false; }
}
重载应该按一个字段比较对象,但该字段对其关闭。
bool operator== (book a, book b) {
if (a.code == b.code) { return true; }
else { return false; }
}
重载应该按一个字段比较对象,但该字段对其关闭。
我正在尝试重载 <=> 运算符,但以下代码会引发编译错误
错误:'operator==' 不匹配(操作数类型为 'example' 和 'example')
struct example {
int a{0};
int b{0};
auto operator <=>(const example& other) const{
return a<=>other.a;
}
};
int main() {
example a{1, 2};
example b{1, 3};
a == b;
return 0;
}
同时,如果我写 auto operator <=>(const example& other) const = default;
,不会有编译错误。但是我不能写默认值,因为我需要稍微修改一下逻辑。<> 运算符起作用。
我专门为该类重载了增量运算符,但使用后缀增量,编译器只显示第一个c1.getCount()
,然后输出:“(进程 17100)退出,代码为 -1073741571。”
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
class Counter
{
private:
int count;
public:
Counter() : count(0)
{}
Counter(int c) : count(c)
{}
int getCount()
{
return count;
}
Counter operator++ ()
{
return Counter(++count);
}
Counter operator++ (int)
{
return operator++ (count++);
}
};
int main()
{
Counter c1;
Counter c2;
cout << c1.getCount() << endl;
++c1;
c2++;
cout << c2.getCount() << endl;
cout << c1.getCount() << endl;
return 0;
}`
请帮帮我。所需的变量没有重载。
类用户:(继承自 Account)
void User::resetAccount(){
!Account();
}
类账户(继承自 Money)
//Account.h
class Account{
private:
string fio;
long id; //id
int pin;
Money m;
public:
Account();
Account(string FIO, long Ident, int Pin, Money M);
Account operator!();
//Account.cpp
Account Account::operator!(){
this->m.setSum(0);
return *this;
}
Money 中的 setSum() 方法可以正常工作。谢谢你。
我想在 rust`e 中编写一些代码,但遇到了一些困难。我用三个相同类型的字段创建了一个结构向量,为此我需要重载加法、减法和乘法运算符。尽管我根据书籍和互联网上的示例做了所有事情,但尝试重载加法运算符失败了。这是代码本身:
use std::ops::Add;
struct Vector<T> {
x1: T,
x2: T,
x3: T,
}
impl<T> Add<T> for Vector<T>
{
type Output = Vector<T>;
fn add(self, rhs: Vector<T>) -> Vector<T> {
Vector {x1: self.x1 + rhs.x1, x2: self.x2 + rhs.x2, x3: self.x3 + rhs.x3};
}
}
fn main() {
let vector1 = Vector { x1: 5.6, x2: 7.2, x3: 2.5 };
let vector2 = Vector { x1: -0.1, x2: 10.9, x3: 3.3 };
println!("Вектор 1: ({}, {}, {})", vector1.x1, vector1.x2, vector1.x3);
println!("Вектор 2: ({}, {}, {})", vector2.x1, vector2.x2, vector2.x3);
let vector3 = vector1 + vector2;
println!("Сумма векторов: ({}, {}, {})", vector3.x1, vector3.x2, vector3.x3);
}
错误:
error[E0053]: method `add` has an incompatible type for trait
--> main.rs:13:5
|
13 | / fn add(self, rhs: Vector<T>) -> Vector<T> {
14 | | Vector {x1: self.x1 + rhs.x1, x2: self.x2 + rhs.x2, x3: self.x3 + rhs.x3};
15 | | }
| |_____^ expected type parameter, found struct `Vector`
|
= note: expected type `fn(Vector<T>, T) -> Vector<T>`
found type `fn(Vector<T>, Vector<T>) -> Vector<T>`
error: aborting due to previous error(s)
在在线编译器中编写和编译。提前致谢。