小编Reu*_*tta的帖子

使用空的默认构造函数时成员中存在垃圾值的问题

我正在尝试使用默认构造函数创建一个非常基本的类:

    class Point {
    public:
          Point() = default;//con 1
          explicit Point(double x): x_axis(x), y_axis(0){}//con 2
          Point(const Point &other) = default;
          ~Point() = default;
    private:
           double x_axis;
           double y_axis;
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试在main()函数中使用默认构造函数时,它会生成一个随机垃圾值x_axis

    Point p1;//generates random value
    Point p2{};//works as intended
Run Code Online (Sandbox Code Playgroud)

这是为什么?当我像这样使用其他构造函数(con 2)时:

    explicit Point(double x = 0): x_axis(x), y_axis(0){}
Run Code Online (Sandbox Code Playgroud)

它们都按预期工作。

  1. 为什么在第一次没有括号的尝试中,它会生成一个随机值,但{} 有效,但在第二次尝试中它们都有效?
  2. 什么是调用默认构造函数{}

c++ oop c++11

2
推荐指数
1
解决办法
80
查看次数

无法从集合中删除shared_ptr

我试图拥有一个带有一组指向另一个对象的指针的对象。当我尝试删除集合的值时,我收到错误并崩溃,我真的不知道是什么原因导致的。这是库,之后是主要功能:当我尝试运行它时,它会执行它应该执行的所有操作,当它到达removeemployee时,它崩溃并发出以下内容:进程已完成,退出代码-1073740940(0xC0000374)

如果重要的话,我在 clion 上运行它,并在 c++11 中运行它。

#include <ostream>
#include <iostream>
#include "Manager.h"

Manager::Manager(int id, string firstName, string lastName, int birthYear)
        : Citizen(id, firstName, lastName,birthYear), salary(0), employees(), work_flag(false) {}

int Manager::getSalary() const {
    return salary;
}

void Manager::setSalary(int _salary) {
    if((salary + _salary) < 0){
        salary = 0;
    }else {
        salary += _salary;
    }
}

void Manager::addEmployee(Employee* employee_add) {
    shared_ptr<Employee> employee(employee_add);
    if(employees.find(employee) != employees.end()){
        throw mtm::EmployeeAlreadyExists();
    }
    employees.emplace(employee);
}

//this is the function

void Manager::removeEmployee(int id) {
    for(auto it = employees.begin(); …
Run Code Online (Sandbox Code Playgroud)

c++ set shared-ptr

1
推荐指数
1
解决办法
108
查看次数

标签 统计

c++ ×2

c++11 ×1

oop ×1

set ×1

shared-ptr ×1