我有Mult, Add, Div, Sub, Mod那些需要两个整数并返回其参数结果的函数。还有一个函数Calc,该函数将一个字符作为,Operator并返回一个指针,该函数返回一个整数,并接受两个整数参数,例如Mult。
Mult的第二个参数default这样的函数是So,当我调用时Calc,根据的参数值Calc返回Mult或Add... 的地址,Calc因此我只能传递一个参数。但这不适用于函数指针:
int Add(int x, int y = 2) { // y is default
return x + y;
}
int Mult(int x, int y = 2) { // y is default
return x * y;
}
int Div(int x, int y = 2) { // y is default
return y ? x …Run Code Online (Sandbox Code Playgroud) 我有两节课;Salary旨在保存有关雇员薪水的信息和计算,并且Employee具有类型对象class Salary和一些成员,例如雇员的姓名和地址...
我想做的是防止class Salary被实例化,除了 class Employee。所以我宣布了Salary私有的建设者,并成为Employee的朋友Salary。但是我得到了错误:
class Employee;
class Salary {
public:
private:
Salary() : revenue_{}, cost_{} {}
Salary(int x, int y) : revenue_{ x },
cost_{ y } {
}
int revenue_, cost_;
friend class Employee;
};
class Employee {
public:
std::string name_;
Salary sal;
};
int main(){
Employee emp{}; // "Salary::Salary()" is inaccessible
}
Run Code Online (Sandbox Code Playgroud)如果我向前声明,问题就解决了main:
int main(int, char*[]);
Run Code Online (Sandbox Code Playgroud)
并在Salary中结交main类似的朋友 …
我对左值和右值有一些了解。因此,据我所知,我们不能分配给右值,但是非常量左值是可以的。
#include <iostream>
#include <vector>
int main(){
std::vector<int> v{ 1, 2, 3, 4, 5 };
v.begin() = v.end() - 2;
std::cout << *v.begin() << std::endl; // 1
for (auto const& e : v)
std::cout << e << ", ";// 1, 2, 3, 4, 5,
std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
为什么我可以分配给begin()元素,但对元素却什么也没做?
我对为什么可以使用typedef声明函数感到有些困惑。这是我的示例:
int Add(int a, int b) {
return a + b;
}
int Mult(int a, int b) {
return a * b;
}
typedef int func(int, int);
int main(int argc, char* argv[]){
func Add;
cout << Add(5, 57) << endl;
}
Run Code Online (Sandbox Code Playgroud)
func Add;我可以Add()直接致电时,int上面的意思是什么?
我有一个模拟窗口的程序;所以我将窗口的内容存储在content一种std::string类型的成员数据中:
class Window {
using type_ui = unsigned int;
public:
Window() = default;
Window(type_ui, type_ui, char);
void print()const;
private:
type_ui width_{};
type_ui height_{};
char fill_{};
std::string content_{};
mutable type_ui time_{};
};
Window::Window(type_ui width, type_ui height, char fill) :
width_{ width }, height_{ height }, fill_{ fill },
content_{ width * height, fill } { // compile-time error here?
//content( width * height, fill ) // works ok
}
void Window::print()const {
while (1) {
time_++;
for …Run Code Online (Sandbox Code Playgroud)